package com.mvc.gulimall.product.exception;

import com.mvc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.junit.validator.PublicClassValidator;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;


//日志
@Slf4j
//@ResponseBody
//// 集中异常类的处理  @RestControllerAdvice  是二个类的合体
//@ControllerAdvice(basePackages = "com.mvc.gulimall.product.controller")
@RestControllerAdvice(basePackages = "com.mvc.gulimall.product.controller")
public class GlimallExceptionControllerAvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVailException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String,String> map =new HashMap<>();
        result.getFieldErrors().forEach((fieldError)->{
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(400,"数据校验错误").put("data",map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handException(Throwable e) {

        return R.error();
    }

}
